﻿using BCCommon;
using BCData.Common.UserBankCard;
using BCData.Common.Wallet;
using BCData.Website.User.User;
using BCDto.Common.BankCardDetection;
using BCDto.Common.UserBankCard;
using BCEntity.Common.UserBankCard;
using BCService.Common.Dictionary;
using BCService.CommonService.BankCardDetection;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;

namespace BCService.CommonService.UserBankCard
{
    public class UserBankCardService : IUserBankCardService
    {
        private readonly IUserBankCardData userBankCardData;
        private readonly IUserData userData;
        private readonly IWalletData walletData;
        private readonly IBankCardDetectionService bankCardDetectionService;
        private readonly IDictionaryReferenceService dictionaryReferenceService;
        private readonly IBankCardPatternService bankCardPatternService;

        public UserBankCardService(IUserBankCardData userBankCardData, IUserData userData, IWalletData walletData, 
            IBankCardDetectionService bankCardDetectionService, IDictionaryReferenceService dictionaryReferenceService,
            IBankCardPatternService bankCardPatternService)
        {
            this.userBankCardData = userBankCardData;
            this.userData = userData;
            this.walletData = walletData;
            this.bankCardDetectionService = bankCardDetectionService;
            this.dictionaryReferenceService = dictionaryReferenceService;
            this.bankCardPatternService = bankCardPatternService;
        }

        public UserBankCardDto Create(UserBankCardRequestDto userBankCardRequestDto)
        {
            if (this.userBankCardData.ExistsByBankCardNo(userBankCardRequestDto.BankCardNo))
            {
                throw new ArgumentException("该银行卡已经存在");
            }
            var userEntity = userData.GetUserByUserId(userBankCardRequestDto.UserId).GetAwaiter().GetResult();
            if (userEntity==null)
            {
                throw new ArgumentException("用户ID无效");
            }
            var walletEntity = this.walletData.Get(userBankCardRequestDto.WalletId);
            if (walletEntity == null)
            {
                throw new ArgumentException("钱包ID无效");
            }
            //检测银行卡类型(通过数据库)
             var bankCardTypeDto =  bankCardPatternService.Match(userBankCardRequestDto.BankCardNo);

             if (bankCardTypeDto == null)
             {//数据库找不到则通过支付宝接口判断
                bankCardTypeDto = bankCardPatternService.AlipayBankCardMatch(userBankCardRequestDto.BankCardNo);
                if (bankCardTypeDto == null)
                {
                    throw new ArgumentException("银行卡无效");
                }
             }
            if (bankCardTypeDto.cardType != "DC")
            {
                throw new ArgumentException("仅支持储蓄卡类型，请确认您的银行卡类型");
            }
            var bankNamedics = dictionaryReferenceService.GetByParentNameAsync("BankName").GetAwaiter().GetResult();
            var bankNameDicRef = bankNamedics.Find(c => c.Name == bankCardTypeDto.bankCode);
            if (bankNameDicRef == null)
            {
                throw new ArgumentException("暂不支持的银行卡类型");
            }
            var bankName = bankNameDicRef.ItemValue;
            var bankKeyCode = bankNameDicRef.SearchKey;

            //测试环境暂时关闭银行卡4元素校验
            var bankcarddetectiondto = this.bankCardDetectionService.RealnameAuthentication(userBankCardRequestDto.BankCardNo, userEntity.IdentityCardNo, userEntity.UserName, userEntity.Phone);
            if (bankcarddetectiondto.DetectionResult.respCode != "0000")
            {
                throw new ArgumentException("添加银行卡失败，失败原因：" + bankcarddetectiondto.DetectionResult.respMsg);
            }
            UserBankCardEntity userBankCardEntity = userBankCardRequestDto.As<UserBankCardEntity>();
            userBankCardEntity.RealnameValidationTime = DateTime.Now;
            userBankCardEntity.IsRealnameValidation = true;
            userBankCardEntity.BankKeyCode = bankKeyCode;
            userBankCardEntity.BankName = bankName;

            return this.userBankCardData.Create(userBankCardEntity).As<UserBankCardDto>();
        }

        public int Delete(long userBankCardId)
        {
            if (!this.userBankCardData.ExistsByBankCardId(userBankCardId))
            {
                throw new ArgumentException("该银行卡信息不存在");
            }
            return this.userBankCardData.Delete(userBankCardId);
        }

        public BankCardTypeInfoDto DetectionBankCard(string bankCardNo)
        {
            //检测银行卡类型(通过数据库)
            var bankCardTypeDto = bankCardPatternService.Match(bankCardNo);

            if (bankCardTypeDto == null)
            {//数据库找不到则通过支付宝接口判断
                bankCardTypeDto = bankCardPatternService.AlipayBankCardMatch(bankCardNo);
                if (bankCardTypeDto == null)
                {
                    throw new ArgumentException("银行卡无效");
                }
            }
            if (bankCardTypeDto.cardType != "DC")
            {
                throw new ArgumentException("仅支持储蓄卡类型，请确认您的银行卡类型");
            }
            var bankNamedics = dictionaryReferenceService.GetByParentNameAsync("BankName").GetAwaiter().GetResult();
            var bankNameDicRef = bankNamedics.Find(c => c.Name == bankCardTypeDto.bankCode);
            if (bankNameDicRef == null)
            {
                throw new ArgumentException("暂不支持的银行卡类型");
            }
            var bankName = bankNameDicRef.ItemValue;

            return new BankCardTypeInfoDto
            {
                bankCardNo = StringUtils.BankCardWithSpecialChar(bankCardNo),
                bankName = bankName,
                bankCode = bankCardTypeDto.bankCode,
                cardType = bankCardTypeDto.cardType
            };
        }

        public UserBankCardDto Get(long userBankCardId)
        {
            var dto = this.userBankCardData.Get(userBankCardId).As<UserBankCardDto>();
            dto.BankCardNo = StringUtils.BankCardWithSpecialChar(dto.BankCardNo);
            return dto;
        }

        public PageableList<UserBankCardDto> List(string userName, string phone, string identityCardNo, string bankCardNo, bool? ascending, int pageIndex, int pageSize, long? userId, long? walletId)
        {
            var list = this.userBankCardData.List(userName, phone, identityCardNo,bankCardNo,ascending, pageIndex, pageSize ,out int dadaCount,userId,walletId);
            var dtos= new  PageableList<UserBankCardDto>
            {
                Count = dadaCount,
                Items = list.Select(p => p.As<UserBankCardDto>())
            };
            List<UserBankCardDto> userBankCardDtos = new List<UserBankCardDto>();
            foreach (var item in dtos.Items)
            {
                item.BankCardNo = StringUtils.BankCardWithSpecialChar(item.BankCardNo);
                userBankCardDtos.Add(item);
            }
            dtos.Items = userBankCardDtos;
            return dtos;
        }

        public int RealNameValidation(long userBankCardId, DateTime realnameValidationTime)
        {
            if (!this.userBankCardData.ExistsByBankCardId(userBankCardId))
            {
                throw new ArgumentException("该银行卡信息不存在");
            }
            return this.userBankCardData.RealNameValidation(userBankCardId, realnameValidationTime);

        }

        public UserBankCardDto Update(long userBankCardId, UserBankCardRequestDto userBankCardRequestDto)
        {
            if (!this.userBankCardData.ExistsByBankCardId(userBankCardId))
            {
                throw new ArgumentException("该银行卡信息不存在");
            }
            UserBankCardEntity userBankCardEntity = userBankCardRequestDto.As<UserBankCardEntity>();
            userBankCardEntity.UserBankCardId = userBankCardId;
            var dto = this.userBankCardData.Update(userBankCardEntity).As<UserBankCardDto>();
            dto.BankCardNo = StringUtils.BankCardWithSpecialChar(dto.BankCardNo);
            return dto;
        }
    }
}
